package com.truongnha.clienttn.presentation.fragment;

import java.util.ArrayList;
import java.util.List;

import com.truongnha.clienttn.R;
import com.truongnha.clienttn.business.model.AttendModel;
import com.truongnha.clienttn.business.service.AttendService;
import com.truongnha.clienttn.presentation.CheckNetwork;
import com.truongnha.clienttn.presentation.adapter.AttendAdapter;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;

public class StudentAttendanceFragment extends Fragment {

	private Intent doneLoading;
	private List<AttendModel> list = new ArrayList<AttendModel>();
	private AttendAdapter attendAdapter;

	private ListView grid;
	private LinearLayout alert;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.student_attendance_template,
				container, false);
		new getAttendanceTask().execute();
		grid = (ListView) view.findViewById(R.id.attendance_grid);
		alert = (LinearLayout) view.findViewById(R.id.alertLinearLayout);
		if (!CheckNetwork.isAvailable(true))
			alert.setVisibility(1);
		attendAdapter = new AttendAdapter(getActivity(), list);
		grid.setAdapter(attendAdapter);

		return view;
	}

	class getAttendanceTask extends AsyncTask<String, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			doneLoading = new Intent();
			doneLoading.setAction("DONE_LOADING_ACTION");
			doneLoading.putExtra("doneLoading", false);
			getActivity().getApplicationContext().sendBroadcast(doneLoading);
		}

		@Override
		protected Void doInBackground(String... params) {
			try {
				list.clear();
				AttendService attendService = new AttendService(getActivity()
						.getApplicationContext());
				if (CheckNetwork.isAvailable(true))
					attendService.getDataFromServer();
				attendService.getAll(list);
			} catch (Exception e) {
				Log.e("log error",
						"error in student attend fragment" + e.toString());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// Broadcast to main activity when done loading
			doneLoading = new Intent();
			doneLoading.setAction("DONE_LOADING_ACTION");
			doneLoading.putExtra("doneLoading", true);
			getActivity().getApplicationContext().sendBroadcast(doneLoading);
			attendAdapter.notifyDataSetChanged();
			// grid.smoothScrollToPosition(list.size());
		}
	}// End class getTermTask

}